package com.sikao.app.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cnzhizi.wheelpop.model.OneModel;
import com.cnzhizi.wheelpop.model.ThreeModel;
import com.cnzhizi.wheelpop.model.TwoModel;
import com.cnzhizi.wheelpop.ui.SkmModiPopup;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sikao.app.R;
import com.sikao.app.bean.AreaBean;
import com.sikao.app.bean.AreaSubmitBean;
import com.sikao.app.bean.Bean;
import com.sikao.app.bean.SellerApplyInfSubmitBean;
import com.sikao.app.bean.UploadPicturesBean;
import com.sikao.app.bean.UserInfoBean;
import com.sikao.app.dao.AreaBeanModel;
import com.sikao.app.dao.BasicInfModel;
import com.sikao.app.dao.SubmitSellerApplyInfModel;
import com.sikao.app.dao.UploadPicturesModel;
import com.sikao.app.net.HttpApi;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.AndroidBug5497Workaround;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sikao.app.R.id.iv;

public class CompanyApplyActivity extends BaseActivity implements View.OnClickListener, TextWatcher {

	private TextView titleTv;
	private ImageView backIv;

	private EditText nameEt;
	private RelativeLayout selectLocationRl;
	private TextView companyAddressTv;
	private EditText companyAddressEt;
	private EditText mobphoneEt;//移动电话
	private EditText phoneNumberEt;
	private EditText companyIntroductionEt;
	private ImageView iv1;
	private ImageView iv2;
	private ImageView iv3;
	private Button saveBtn;
	private int applyType;  //0首次填写提交，1、审核中，2、通过审核不可更改,3、审核失败
	private String string1, string2, string3;
	private String id1, id2, id3;
	private String picturePath1, picturePath2, picturePath3;

	private BasicInfModel basicInfModel;
	private UploadPicturesModel uploadPicturesModel1, uploadPicturesModel2, uploadPicturesModel3;
	private SubmitSellerApplyInfModel submitSellerApplyInfModel;
	private SellerApplyInfSubmitBean sellerApplyInfSubmitBean = new SellerApplyInfSubmitBean();
	private ImageLoader imageLoader = ImageLoader.getInstance();
	public static final int REQUEST_GET_PHOTO1 = 17;
	public static final int REQUEST_GET_PHOTO2 = 18;
	public static final int REQUEST_GET_PHOTO3 = 19;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_company_apply);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initData() {

	}

	@Override
	protected void initView() {
		titleTv = (TextView) findViewById(R.id.title_middle_tv);
		backIv = (ImageView) findViewById(R.id.title_left_img);

		nameEt = (EditText) findViewById(R.id.name_et);
		selectLocationRl = (RelativeLayout) findViewById(R.id.select_location_rl);
		companyAddressTv = (TextView) findViewById(R.id.company_address_tv);
		companyAddressEt = (EditText) findViewById(R.id.company_address_et);
		mobphoneEt = (EditText) findViewById(R.id.mobphone_et);
		phoneNumberEt = (EditText) findViewById(R.id.phone_number_et);
		companyIntroductionEt = (EditText) findViewById(R.id.company_introduction_et);
		iv1 = (ImageView) findViewById(R.id.iv1);
		iv2 = (ImageView) findViewById(R.id.iv2);
		iv3 = (ImageView) findViewById(R.id.iv3);
		saveBtn = (Button) findViewById(R.id.save_btn);
	}

	@Override
	protected void initListener() {
		selectLocationRl.setOnClickListener(this);
		iv1.setOnClickListener(this);
		iv2.setOnClickListener(this);
		iv3.setOnClickListener(this);
		saveBtn.setOnClickListener(this);
		backIv.setOnClickListener(this);
	}

	@Override
	protected void init() {
		titleTv.setText("企业认证");
		backIv.setVisibility(View.VISIBLE);

			basicInfModel = new BasicInfModel(this, new OnNetBackListener<UserInfoBean>() {
				@Override
				public void netBack(UserInfoBean data) {
					if (data == null) {
						return;
					}
					//0首次填写提交，1、审核中，2、通过审核不可更改,3、审核失败
					if (data.getStatus().equals("1")) {
						UserInfoBean.ResBean bean = data.getRes();
						if (bean.getCheck_status().equals("2")) {
							ConstantClass.isSeller = true;
						}
						if (Integer.parseInt(bean.getCheck_status()) > 0) {
							nameEt.setText(bean.getCom_name());
							companyAddressTv.setText(bean.getCom_area_name());
							companyAddressEt.setText(bean.getCom_add());
							phoneNumberEt.setText(bean.getCom_phone());
							companyIntroductionEt.setText(bean.getCom_cont());
							string1 = bean.getImg_src().get(0);
							string2 = bean.getImg_src().get(1);
							string3 = bean.getImg_src().get(2);
							sellerApplyInfSubmitBean.setProvince(bean.getProvince());
							sellerApplyInfSubmitBean.setCity(bean.getCity());
							sellerApplyInfSubmitBean.setCounty(bean.getCounty());
							imageLoader.displayImage(HttpApi.BANNERUTL + bean.getImg_src().get(0), iv1);
							imageLoader.displayImage(HttpApi.BANNERUTL + bean.getImg_src().get(1), iv2);
							imageLoader.displayImage(HttpApi.BANNERUTL + bean.getImg_src().get(2), iv3);
							ConstantClass.userName = bean.getName();
							ConstantClass.phoneNumber = bean.getPhone();
							ConstantClass.imgUrl = bean.getImgsrc();
						}
						if (bean.getCheck_status().equals("1")) {
							applyType = 1;
							saveBtn.setTextColor(getResources().getColor(R.color.text_red));
							saveBtn.setText("审核中");
							saveBtn.setBackgroundResource(R.drawable.shap_gray_solid_five);
							setClickable(false);
						} else if (Integer.parseInt(bean.getCheck_status()) <= 0) {
							applyType = 0;
						} else if (bean.getCheck_status().equals("2")) {
							applyType = 2;
							saveBtn.setBackgroundResource(R.drawable.shap_gray_solid_five);
							saveBtn.setTextColor(getResources().getColor(R.color.text_gray));
							saveBtn.setText("审核通过");
							saveBtn.setEnabled(false);
							setClickable(false);
						} else {
							applyType = 3;
							saveBtn.setBackgroundResource(R.drawable.shap_gray_solid_five);
							saveBtn.setTextColor(getResources().getColor(R.color.text_gray));
							saveBtn.setText("审核失败，请重新编辑");
							nameEt.addTextChangedListener(CompanyApplyActivity.this);
							companyAddressTv.addTextChangedListener(CompanyApplyActivity.this);
							companyAddressEt.addTextChangedListener(CompanyApplyActivity.this);
							phoneNumberEt.addTextChangedListener(CompanyApplyActivity.this);
							companyIntroductionEt.addTextChangedListener(CompanyApplyActivity.this);
						}
					} else {
						Toast.makeText(CompanyApplyActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});

		basicInfModel.request("{}", true);
	}

	private void sellerApply() {
		if (!checkInput()) {
			return;
		}
		if (submitSellerApplyInfModel == null) {

			submitSellerApplyInfModel = new SubmitSellerApplyInfModel(this, new OnNetBackListener<Bean>() {
				@Override
				public void netBack(Bean data) {
					if (data == null) {
						return;
					}
					if (data.getStatus().equals("1")) {
						Toast.makeText(CompanyApplyActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
						applyType = 1;
						saveBtn.setTextColor(getResources().getColor(R.color.text_red));
						saveBtn.setText("审核中");
						saveBtn.setBackgroundResource(R.drawable.shap_gray_solid_five);
						setClickable(false);
					} else {
						Toast.makeText(CompanyApplyActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
		sellerApplyInfSubmitBean.setCom_name(nameEt.getText().toString());

		sellerApplyInfSubmitBean.setCom_add(companyAddressEt.getText().toString());
		sellerApplyInfSubmitBean.setCom_cont(companyIntroductionEt.getText().toString());
		//这里需要重新生成 bean 带移动电话的 sellerApplyInfSubmitBean.setMobphone(mobphoneEt.getText().toString());

		sellerApplyInfSubmitBean.setCom_phone(phoneNumberEt.getText().toString());
		sellerApplyInfSubmitBean.setImgname(id1 + "," + id2 + "," + id3);
		sellerApplyInfSubmitBean.setImgsrc(string1 + "," + string2 + "," + string3);
		submitSellerApplyInfModel.request(JSONUtil.toJSON(sellerApplyInfSubmitBean), true);
	}

	private boolean checkInput() {
		if (TextUtils.isEmpty(nameEt.getText().toString())) {
			Toast.makeText(this, "请填写企业名称", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(mobphoneEt.getText().toString())) {
			Toast.makeText(this, "请填写移动电话", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(phoneNumberEt.getText().toString())) {
			Toast.makeText(this, "请填写企业电话", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(companyAddressTv.getText().toString())) {
			Toast.makeText(this, "请选择企业地址", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(companyAddressEt.getText().toString())) {
			Toast.makeText(this, "请填写详细地址", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(companyIntroductionEt.getText().toString())) {
			Toast.makeText(this, "请填写企业介绍", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(string1)) {
			Toast.makeText(this, "请上传营业执照副本", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(string2)) {
			Toast.makeText(this, "请上传法人身份证正面", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(string3)) {
			Toast.makeText(this, "请上传法人身份证背面", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.title_left_img:
				finish();
				break;
			case R.id.select_location_rl:
				chooseDeliveryArea();
				break;
			case R.id.iv1:
				Intent intent1 = new Intent(CompanyApplyActivity.this, SelectPictureActivity.class);
				startActivityForResult(intent1, REQUEST_GET_PHOTO1);
				overridePendingTransition(R.anim.bottom_push_in, R.anim.bottom_push_out);
				break;
			case R.id.iv2:
				Intent intent2 = new Intent(CompanyApplyActivity.this, SelectPictureActivity.class);
				startActivityForResult(intent2, REQUEST_GET_PHOTO2);
				overridePendingTransition(R.anim.bottom_push_in, R.anim.bottom_push_out);
				break;
			case R.id.iv3:
				Intent intent3 = new Intent(CompanyApplyActivity.this, SelectPictureActivity.class);
				startActivityForResult(intent3, REQUEST_GET_PHOTO3);
				overridePendingTransition(R.anim.bottom_push_in, R.anim.bottom_push_out);
				break;
			case R.id.save_btn:
				sellerApply();
				break;
			default:
				break;
		}
	}

	private void setClickable(boolean clickable) {
		selectLocationRl.setEnabled(clickable);

		iv1.setEnabled(clickable);
		iv2.setEnabled(clickable);
		iv3.setEnabled(clickable);

		nameEt.setEnabled(clickable);
		companyAddressEt.setEnabled(clickable);
		mobphoneEt.setEnabled(clickable);
		phoneNumberEt.setEnabled(clickable);
		companyIntroductionEt.setEnabled(clickable);
		saveBtn.setClickable(clickable);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	@Override
	public void afterTextChanged(Editable s) {
		if (applyType == 3) {
			saveBtn.setBackgroundResource(R.drawable.selector_btn_red_five);
			saveBtn.setTextColor(getResources().getColor(R.color.white));
			saveBtn.setText("提交更改");
			saveBtn.setEnabled(true);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case REQUEST_GET_PHOTO1:
					picturePath1 = data.getStringExtra("path");
					uploadPicture1("picture1.png", picturePath1);
					break;
				case REQUEST_GET_PHOTO2:
					picturePath2 = data.getStringExtra("path");
					uploadPicture2("picture2.png", picturePath2);
					break;
				case REQUEST_GET_PHOTO3:
					picturePath3 = data.getStringExtra("path");
					uploadPicture3("picture3.png", picturePath3);
					break;
				default:
					break;
			}
		}
	}

	private void uploadPicture1(String type, String picturePath) {
		if (uploadPicturesModel1 == null) {
			uploadPicturesModel1 = new UploadPicturesModel(this, new OnNetBackListener<UploadPicturesBean>() {
				@Override
				public void netBack(UploadPicturesBean data) {
					if (data == null) {
						Toast.makeText(CompanyApplyActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
						return;
					}

					if (data.getStatus().equals("1")) {
						//imageLoader.displayImage(HttpApi.BANNERUTL + data.getRes().getArr().get(0).getUrl(), iv1);
						imageLoader.displayImage("file://" + picturePath1, iv1);
						string1 = data.getRes().getArr().get(0).getUrl();
						id1 = data.getRes().getArr().get(0).getId();
						if (applyType == 3) {
							saveBtn.setBackgroundResource(R.drawable.selector_btn_red_five);
							saveBtn.setTextColor(getResources().getColor(R.color.white));
							saveBtn.setText("提交更改");
							saveBtn.setEnabled(true);
						}
					}

				}
			});
		}
		Map<String, String> map = new HashMap<>();
		map.put(type, picturePath);
		uploadPicturesModel1.request(map, true);
	}

	private void uploadPicture2(String type, String picturePath) {
		if (uploadPicturesModel2 == null) {
			uploadPicturesModel2 = new UploadPicturesModel(this, new OnNetBackListener<UploadPicturesBean>() {
				@Override
				public void netBack(UploadPicturesBean data) {
					if (data == null) {
						Toast.makeText(CompanyApplyActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
						return;
					}

					if (data.getStatus().equals("1")) {
						imageLoader.displayImage("file://" + picturePath2, iv2);
						string2 = data.getRes().getArr().get(0).getUrl();
						id2 = data.getRes().getArr().get(0).getId();
						if (applyType == 3) {
							saveBtn.setBackgroundResource(R.drawable.selector_btn_red_five);
							saveBtn.setTextColor(getResources().getColor(R.color.white));
							saveBtn.setText("提交更改");
							saveBtn.setEnabled(true);
						}
					}

				}
			});
		}
		Map<String, String> map = new HashMap<>();
		map.put(type, picturePath);
		uploadPicturesModel2.request(map, true);
	}

	private void uploadPicture3(String type, String picturePath) {
		if (uploadPicturesModel3 == null) {
			uploadPicturesModel3 = new UploadPicturesModel(this, new OnNetBackListener<UploadPicturesBean>() {
				@Override
				public void netBack(UploadPicturesBean data) {
					if (data == null) {
						Toast.makeText(CompanyApplyActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
						return;
					}

					if (data.getStatus().equals("1")) {
						imageLoader.displayImage("file://" + picturePath3, iv3);
						string3 = data.getRes().getArr().get(0).getUrl();
						id3 = data.getRes().getArr().get(0).getId();
						if (applyType == 3) {
							saveBtn.setBackgroundResource(R.drawable.selector_btn_red_five);
							saveBtn.setTextColor(getResources().getColor(R.color.white));
							saveBtn.setText("提交更改");
							saveBtn.setEnabled(true);
						}
					}

				}
			});
		}
		Map<String, String> map = new HashMap<>();
		map.put(type, picturePath);
		uploadPicturesModel3.request(map, true);
	}

	final List<OneModel> oneModelListForDeliveryArea = new ArrayList<OneModel>();//企业地址滚轮一级

	/**
	 * 企业地址
	 */
	private void chooseDeliveryArea() {
		//区域
		if (ConstantClass.areaBean == null) {
			AreaSubmitBean areaSubmitBean = new AreaSubmitBean("recursion");
			new AreaBeanModel(this, new OnNetBackListener<AreaBean>() {
				@Override
				public void netBack(AreaBean data) {
					if (data == null) {

					} else {
						if (data.getStatus() == 1) {
							initAreaData(data);
							ConstantClass.areaBean = data;
						} else {
							Toast.makeText(CompanyApplyActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
						}
					}
				}
			}).request(JSONUtil.toJSON(areaSubmitBean), true);
		} else {
			//已经有不请求网络
			initAreaData(ConstantClass.areaBean);
		}
	}

	/**
	 * 拆分地区分类数据
	 *
	 * @param data
	 */
	private void initAreaData(AreaBean data) {
		oneModelListForDeliveryArea.clear();
		//一级
		List<AreaBean.ResBean> res = data.getRes();//原始数据
		Utils.showLog("==============res.size=" + res.size());
		for (int i = 0; i < res.size(); i++) {
			OneModel oneModel = new OneModel();
			oneModel.setId(res.get(i).getId());
			oneModel.setName(res.get(i).getName());

			//  二级
			List<TwoModel> twoModelList2 = new ArrayList<TwoModel>();//滚轮二级
			for (int j = 0; j < res.get(i).getChild().size(); j++) {

				TwoModel twoModel = new TwoModel();
				twoModel.setId(res.get(i).getChild().get(j).getId());
				twoModel.setName(res.get(i).getChild().get(j).getName());

				List<ThreeModel> threeModelList3 = new ArrayList<ThreeModel>();//滚轮三级
				for (int h = 0; h < res.get(i).getChild().get(j).getChild().size(); h++) {
					ThreeModel threeModel = new ThreeModel();
					threeModel.setId(res.get(i).getChild().get(j).getChild().get(h).getId());
					threeModel.setName(res.get(i).getChild().get(j).getChild().get(h).getName());
					threeModelList3.add(threeModel);

					twoModel.setThreeModelList(threeModelList3);

				}
				twoModelList2.add(twoModel);
			}
			oneModel.setTwoModelList(twoModelList2);
			oneModelListForDeliveryArea.add(oneModel);
		}
		showPop(oneModelListForDeliveryArea, companyAddressTv, 3);
	}

	SkmModiPopup skmModiPopup;

	private void showPop(List<OneModel> oneModelList, View view, int level) {
		skmModiPopup = new SkmModiPopup(this, skmPopOnClickListener, oneModelList, "选择", level, view);
		skmModiPopup.showAtLocation(findViewById(R.id.rl_company_apply),
				Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	public SkmModiPopup.SkmPopOnClickListener skmPopOnClickListener = new SkmModiPopup.SkmPopOnClickListener() {

		@Override
		public void myOnClick(int pOneCurrent, int pTwoCurrent, int pThreeCurrent, View v, View root) {
			skmModiPopup.dismiss();
			switch (root.getId()) {
				case R.id.company_address_tv://交割地
					   /* "deliveryArea": "山东省青岛市市南区",
						"province": "28",
                        "city": "128",
                        "county": "512",*/
					//Toast.makeText(ReleaseGoodsActivity.this, "一级：id:" + oneModelList.get(pOneCurrent).getId() + " name:" + oneModelList.get(pOneCurrent).getName()+ " 二级：id" + oneModelList.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getId() + "name:" + oneModelList.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getName() + " 三级：id" + oneModelList.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getThreeModelList().get(pThreeCurrent).getId() + "name:" + oneModelList.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getThreeModelList().get(pThreeCurrent).getName() , Toast.LENGTH_SHORT).show();
					String deliveryArea = oneModelListForDeliveryArea.get(pOneCurrent).getName() + oneModelListForDeliveryArea.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getName() + oneModelListForDeliveryArea.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getThreeModelList().get(pThreeCurrent).getName();
					String province = oneModelListForDeliveryArea.get(pOneCurrent).getId();
					String city = oneModelListForDeliveryArea.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getId();
					String county = oneModelListForDeliveryArea.get(pOneCurrent).getTwoModelList().get(pTwoCurrent).getThreeModelList().get(pThreeCurrent).getId();

					companyAddressTv.setText(deliveryArea);
					//保存交割地信息的值
					sellerApplyInfSubmitBean.setProvince(province);
					sellerApplyInfSubmitBean.setCity(city);
					sellerApplyInfSubmitBean.setCounty(county);

					break;
				default:
					break;
			}
		}
	};
}
